﻿//客户端裸钻
var SortJson = [];//排序用的数组
var app_url=location.origin;
var Customer_id="";
var PlaceOrder=false;//代下单
var MOBILE=true;
var TYPE='';
(function () {
    var stock = {
        init: function () {
            args = GetUrlParms();
            if(args["type"]!=undefined){
                TYPE = args["type"];//产品ID
            }

            TEAM=getUrlParam("team");
            Customer_id=getUrlParam("cid");
            if(Customer_id!="" && Customer_id!=null){
                PlaceOrder=true;//代下单
            }
            this.bindEvents();



            //筛选条件
            // var diaList = localStorage.getItem("diaList");
            // if(diaList){
            //     this.getStock(diaList);
            // }else {
                getStock();
            // }

            if(TEAM==0){
             this.getStockCount();
            }
        },

        bindEvents: function () {
            var self = this;

            if(PlaceOrder==true){
                $('#place_order_btn').html('<span id="buy_btn">'+_("立即购买")+'(<b style="font-size:12px" id="_realName"></b>)'+'</span>');
                // $('#place_order_btn').html('<span id="buy_btn">'+_("立即购买")+'</span>');
            }
            //代下单立即定购显示名字
            if(TEAM==3){
                $("#_realName").text(NullFormat(getUrlParam('userName')));
            }
            if(APP){
                var h=$(".subnavbar").height()-$("#product_table_fixed").height()-2;
            }else{
                var h=$(".subnavbar").height()+44-$("#product_table_fixed").height()-2;
            }

            $("#app_no_header").css("padding-top",h);
            //点击排序
            $("#product_table_fixed").on("click","th", function () {
                var sort = $(this).children("i");
                var sort_asc=false;//排序，false为正序，true为反序
                //排序方法
                var sortBy = function (filed, rev, primer) {
                    rev = (rev) ? -1 : 1;
                    return function (a, b) {
                        a = a[filed];
                        b = b[filed];
                        if (typeof (primer) != 'undefined') {
                            a = primer(a);
                            b = primer(b);
                        }
                        if (a < b) { return rev * -1; }
                        if (a > b) { return rev * 1; }
                        return 1;
                    }
                };
                if (sort.length>0) {
                    var iSort = $(this).children("i");
                    var sortName = iSort.attr("data-sort");//排序的字段名
                    var sortDirect = iSort.attr("data-sort-direct");
                    //升序
                    if (!sortDirect) {
                        sortDirect = "asc";//页面样式
                        SortJson.sort(sortBy(sortName, sort_asc, parseFloat));//排序方法
                        bindingInventory(SortJson);//渲染页面
                    }else{
                        sortDirect = "";//页面样式
                        SortJson.sort(sortBy(sortName, true, parseFloat));
                        bindingInventory(SortJson);//渲染页面
                    }

                    iSort.addClass("sort_" + sortDirect);//修改样式
                    $("th i").not(iSort).removeClass("sort_asc").removeClass("sort_desc").removeClass("sort_normal");
                    $("th i[data-sort='" + sortName + "']").addClass("sort_" + sortDirect).attr("data-sort-direct", sortDirect);
                }


            });
            //复制表头并固定
//          notbtn=1;
//          chromatable("product_table");
//          $(window).resize(function () {
//              updateHeader("product_table");
//          });
            //筛选
            $("#term_app_btn").on("click",function(){
                if(PlaceOrder==true){
                    location.href="/Team/DiasFilter?team=3&cid="+Customer_id+'&userName='+NullFormat(getUrlParam('userName'));
                }else{
                    location.href="/Team/DiasFilter?team="+TEAM;
                }
            });
            //点击行详情关闭
            $("#product_table").on("click", ".stock_detail", function () {
                //  $(this).hide();
            });
            //点击行展开详情
            $("#product_table").on("click", "tr.data_tr td", function (event) {
                var td_input = $(this).index();
                if (td_input == 0 || td_input==1 || td_input==2) {
                    //勾选框不展开详情
                } else {
                    $(this).parent("tr").next(".stock_detail").slideToggle(0);
                }

            });
            //列表的勾选框
            $("#product_table").on("click",".check_rel",function(){
                $(this).children().find("span").toggleClass("selected");
                $(this).parent("tr").toggleClass("tr_select_color");
            });
            $("#product_table").on("click","td.check_list_td",function(){
                $(this).prev().find("span").toggleClass("selected");
                $(this).parent("tr").toggleClass("tr_select_color");
            });
            $("#product_table").on("click","td.check_list_td2",function(){
                $(this).prev().prev().find("span").toggleClass("selected");
                $(this).parent("tr").toggleClass("tr_select_color");
            });
            //查看购物车
            $("#go_to_cart").on("click",function(){
                var linkUrl="/Customer/DiaCart";
                if(APP){
                    var appJson={};
                    appJson.title=_("裸钻购物车");
                    appJson.function_menu="shopping_cart";
                    appJson.url=app_url+linkUrl;
                    YiYi_APP.showExistingPage(JSON.stringify(appJson));
                }else{
                    location.href=linkUrl;
                }
            });

            //查看订单
            $("#go_app_cart").on("click",function(){
                var linkUrl="/Customer/DiaOrder";
                if(APP){
                    var appJson={};
                    appJson.title=_("订单管理");
                    appJson.function_menu="order";
                    appJson.url=app_url+linkUrl;
                    YiYi_APP.showExistingPage(JSON.stringify(appJson));
                }else{
                    location.href=linkUrl;
                }
            });

            //加入购物车
            $("#add_cart_btn").on("click", function () {
                self.multiAddToCart();
            });
            //购买
            $(".product_btn_box").on("click","#buy_btn",function(){
                var cartlistCb = $("#stock_body .check_rel .check_list_box span.selected");//tbody中checked的
                if (cartlistCb.length == 0) {
                    toast(_("请选择"));
                } else {
                    if(PlaceOrder==true){//代下单客户的ID
                        var link_url="/Customer/SubmitDiaOrder?type=1&cid="+Customer_id+'&userName='+NullFormat(getUrlParam('userName'))
                    }else{
                        var link_url="/Customer/SubmitDiaOrder?type=1";
                    }
                    var orderJson={};
                    orderJson.orderID = [];
                    orderJson.type="stocks";
                    orderJson.form="stocks";
                    orderJson.ConfirmUSD=[];//usd 数组
                    orderJson.ConfirmPrice=[];//rmb 数组
                    var z=0;//是否循环完
                    for (var i = 0; i < cartlistCb.length; i++) {
                        orderJson.orderID.push(cartlistCb[i].lang);
                        orderJson.ConfirmUSD.push(Number(cartlistCb[i].getAttribute("data-usd")));
                        orderJson.ConfirmPrice.push(Number(cartlistCb[i].getAttribute("data-rmb")));
                        z++;
                    }
                    if(z==cartlistCb.length){
                        if(APP){
                            var appJson={};
                            appJson.title=_("确认下单");
                            appJson.url=app_url+link_url;
                            appJson.content=JSON.stringify(orderJson);
                            YiYi_APP.submitOrder(JSON.stringify(appJson))
                        }else{
                            var action=link_url;
                            form = $("<form method='post' id='params_form' action='"+action+"'>"+
                                "<input type='text' value='"+JSON.stringify(orderJson)+"' name='params'></form>")
                            $("#form_box").html(form);
                            $("#params_form").submit();
                        }
                    }
                }
            });


            //跳到证书
            $("#stock_body").on("click","a.cert_link_btn",function(){
                var link_url=$(this).attr("data-href");
                if(APP){
                    var appJson={};
                    appJson.title=_("证书");
                    appJson.url=app_url+link_url;
                    YiYi_APP.showNewPage(JSON.stringify(appJson));
                }else{
                    location.href=link_url;
                }
            });

            $("#product_table").on("click",".ImageIcon",function(){
                var params = {};
                params.InventoryID = $(this).parent().attr("data-value");
                params.HasImage = 1
                self.getImages(params);
            });

            $("#product_table").on("click",".VideoIcon",function(){
                var params = {};
                params.InventoryID = $(this).parent().attr("data-value");
                params.HasVideo = 1
                self.getImages(params);
            });

            //去掉数组里的空值
            Array.prototype.clean = function(deleteValue) {
                for (var i = 0; i < this.length; i++) {
                    if (this[i] == deleteValue) {
                        this.splice(i, 1);//返回指定的元素
                        i--;
                    }
                }
                return this;
            }
        },

        // 获取图片地址
        getImages:function(params){
            var self = this;
            myApp.showIndicator();//显示加载中
            if(TEAM==0){
                var imagesUrl="/Customer/GetImgInfo";//客户端裸钻图片
            }else{
                var imagesUrl="/Team/GetImgInfo";//团队端裸钻图片
            }
            $.ajax({
                url: imagesUrl,//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(params),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                    if (_result.msgcode == true) {
                        myApp.hideIndicator();//隐藏加载中
                        if(params.HasImage==1){
                            var data=_result.msginfo;
                            imgs = data.split(",");
                            imgArray=[];
                            for (var i=0; i< imgs.length;i++) {
                                if (imgs[i].length > 10) {
                                    var big = imgs[i].replace('800x800', '1920x1920');
                                    imgArray.push(big)
                                }else{
                                    var img_null='/images/no_img.jpg';
                                    imgArray.push(img_null)
                                }
                            }
                            //   @*主题色start*@
                            $(document.createElement("script")).attr("src","/Js/ThemesColor.js").appendTo("html");
                            //  @*主题色end*@
                            //放大图片
                            var myPhotoBrowserStandalone = myApp.photoBrowser({
                                photos : imgArray,
                                backLinkText: _('返回'),
                                ofText:"/",
                            });
                            if(APP){
                                var ProductImg={};
                                ProductImg['images']=imgArray;
                                ProductImg['index']=0;
                                YiYi_APP.showImages(JSON.stringify(ProductImg));
                            }else{
                                myPhotoBrowserStandalone.open();
                            }
                        }else if(params.HasVideo==1){
                            var firstImg = _result.msginfo.split(',')[0];
                            if(APP){
                                var ProductVideo={};
                                ProductVideo.url = firstImg;
                                YiYi_APP.showVideo(JSON.stringify(ProductVideo));
                            }else{
                                myApp.popup('.popup-services');
                                var videoHtml=[];
                                videoHtml.push(
                                    '<video src="'+firstImg+'" controls="controls"></video>'
                                );
                                $(".popup-services #PhotoSwipeTarget").html(videoHtml.join(''));
                            }
                        }
                    } else {
                        myApp.alert(_result.msginfo);
                    }
                    myApp.hideIndicator();//隐藏加载中
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    myApp.alert("网络超时，请重试");
                    myApp.hideIndicator();//隐藏加载中
                }
            });
        },
        //获取购物车数量
        getStockCount: function () {
            // myApp.showIndicator();//显示加载中
            var result = {};
            if(TEAM==0){

                result.CustomerID = CustomerID;//客户ID
            }
            result.GoodsType = 1;
            ;
            $.ajax({
                url: "/customer/GetCartNums",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(result),
                contentType: "application/json; charset=utf-8",
                timeout: 30000, //超时时间：30秒
                success: function (result) {
                    var _result=JSON.parse(result);
                    if(_result.msgcode==true){
                        var diaInfo=_result.msginfo;
                        if(diaInfo!=0){
                            $("#diaCount").text("("+_result.msginfo+")")
                        }else{
                            $("#diaCount").text('')
                        }
                    }
                    // myApp.hideIndicator();//隐藏加载中
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    myApp.hideIndicator();//隐藏加载中
                    myApp.alert(_("网络超时，请重试"));
                },
            });
        },



        //加入购物车(单个或多个)
        multiAddToCart:function () {
            var self=this;
            //InventoryIDs值组装 _inventoryIDs="232,324"
            var cartlistCb = $("#stock_body .check_rel .check_list_box span.selected");//checked的
            if (cartlistCb.length == 0) {
                toast(_("请选择"));
            } else {
                myApp.showPreloader(_('正在加入中，请稍等...'));
                var _inventoryIDs = "";
                for (var i = 0; i < cartlistCb.length; i++) {
                    if (i == 0)
                        _inventoryIDs += cartlistCb[i].lang;
                    else
                        _inventoryIDs += "," + cartlistCb[i].lang;
                }

                //判断电脑端1  IOS端2 安卓端3 wap4
                var u = navigator.userAgent, app = navigator.appVersion;
                var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
                var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
                var cartType;
                if (isAndroid) {
                    cartType=3;
                }else  if (isIOS) {
                    cartType=2;
                }else{
                    cartType=4;
                }


                $.ajax({
                    url: "/Customer/AddCart",//提交地址
                    type: "POST",//提交方式
                    data: "{'CustomerID':'" + CustomerID + "','CartType':'" + cartType + "','InventoryIDs':'" + _inventoryIDs + "','GoodsType':'"+1+"'}",
                    contentType: "application/json; charset=utf-8",
                    timeout: 30000, //超时时间：30秒
                    success: function (result) {
                        var res=JSON.parse(result);
                        myApp.hidePreloader();
                        if(res.msgcode==true){
                            myApp.alert(_("成功")+res.succ+","+_("失败")+res.fail);
                        }else{
                            myApp.alert(_(res.msginfo));
                        }
                        self.getStockCount();//购物车数量

                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown){
                        myApp.hidePreloader();
                        myApp.alert("网络超时，请重试");
                    },
                });
            }

        },
    }
    stock.init();
}());
//加载设置的排序
function getGoodsSort(){
    $.ajax({
        url: "/Team/GetGoodsSort",//提交地址
        type: "POST",//提交方式
        data: "{'GoodsType':'"+1+"'}",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var result = eval('(' + result + ')');//eval()解析单个json对象;
            if(result.msgcode==true){
                var data=result.msginfo;
                var sortColumnName=data.SortColumnName;
                var sortMode=data.SortMode;
                if(sortColumnName=="CustomerDiscountReturn" || sortColumnName=="CustomerRMBPerGrain"){
                    sortDiamonds(sortColumnName,sortMode);
                }
            }

        }
    });
}

function sortDiamonds(name,sort_name){

    var sort=$("#product_table_fixed th i[data-sort='"+name+"']");
    $("#product_table_fixed th i[data-sort='"+name+"']").addClass('sort_asc');
    var sort_asc=false;//排序，false为正序，true为反序
    $("#product_table_fixed th i[data-sort='"+name+"']").attr('data-sort-direct',sort_name);
    //排序方法
    var sortBy = function (filed, rev, primer) {
        rev = (rev) ? -1 : 1;
        return function (a, b) {
            a = a[filed];
            b = b[filed];
            if (typeof (primer) != 'undefined') {
                a = primer(a);
                b = primer(b);
            }
            if (a < b) { return rev * -1; }
            if (a > b) { return rev * 1; }
            return 1;
        }
    };
    if (sort.length>0) {
        var iSort =$("#product_table_fixed th i[data-sort='"+name+"']");
        var sortName = iSort.attr("data-sort");//排序的字段名
        var sortDirect = iSort.attr("data-sort-direct");
        $("#stock_body").html('')
        if(sortDirect=='asc'){
            sortDirect='';
        }
        //升序
        if (!sortDirect) {
            sortDirect = "asc";//页面样式
            SortJson.sort(sortBy(sortName, sort_asc, parseFloat));//排序方法
            bindingInventory(SortJson);//渲染页面
        }else{
            sortDirect = "";//页面样式
            SortJson.sort(sortBy(sortName, true, parseFloat));
            bindingInventory(SortJson);//渲染页面
        }

        iSort.addClass("sort_" + sortDirect);//修改样式
        $("th i").not(iSort).removeClass("sort_asc").removeClass("sort_desc").removeClass("sort_normal");
        $("th i[data-sort='" + sortName + "']").addClass("sort_" + sortDirect).attr("data-sort-direct", sortDirect);
    }

}

//获取库存
function getStock() {
    var self = this;
     myApp.showIndicator();//显示加载中

    var params = PARAMS;
    //净度和颜色查询 start
    var _color=0;
    var _clarity=0;
    if(params){
        if(params.Color){
            _color=params.Color.length;
        }
        if(params.Clarity){
            _clarity=params.Clarity.length;
        }
    }

    //净度和颜色查询 end

    if(params!=null){
        //原货号
        if(params.OriginSN!=undefined && params.OriginSN!=""){
            var OriginSNValArray=params.OriginSN.split(" ");
            OriginSNValArray.clean("");
            params.OriginSN=OriginSNValArray;
        }
        //证书号
        if(params.CertNo!=undefined && params.CertNo!=""){
            var CertNoValArray=params.CertNo.split(" ");
            CertNoValArray.clean("");
            params.CertNo=CertNoValArray;
        }
    }else{
        params={};
        params.IsFancy=0;
        if(_color*_clarity>=6){  //颜色和净度组合大于等于6
            params.limit=500;
        }else{
            params.limit=200;
        }
        params.useDict=true;
    }

    params.OnShelves = "1";
    if(TEAM==0){
        params.CustomerID = CustomerID;//客户ID
    }
    if(TEAM==3){
        params.CustomerID=Customer_id;
    }

    if(TEAM==1 || TEAM==3){
        params.UserID=UserID;
    }
    if(_color*_clarity>=6){  //颜色和净度组合大于等于6
        params.limit=500;
    }else{
        params.limit=200;
    }
    //获取排序
    // var requestJson = data?data:JSON.stringify(params);
    var requestJson = JSON.stringify(params);

    if(TEAM==0){
        var submitUrl="/Customer/GetInventoryInfos";
    }else{
        var submitUrl="/Team/GetInventoryInfos";
    }
    $.ajax({
        url: submitUrl,
        data: requestJson,
        type: "post", 
        contentType: "application/json; charset=utf-8",
        timeout: 30000, //超时时间：30秒
        success: function (result) {
            var _result = JSON.parse(result);//eval()解析单个json对象 params.pageIndex
            var tableTbody = $("#stock_body");
            //获取库存成功
            if (_result.msgcode== true) {
                // myApp.hideIndicator();//隐藏加载中
                if(TEAM==0){
                    var $thead= "<th style='width:7%'>"+_("选中")+"</th>"+
                        "<th style='width:8%'>"+_("重量")+"</th>"+
                        "<th style='width:10%'>"+_("颜色")+"</th>"+
                        " <th style='width:10%'>"+_("净度")+"</th>";
                    if(params.IsFancy == 0 && discount_td==true&&CurrentRMB==true && RMBprice_td==true && discountsRMB_td){
                        $thead+="<th style='width:10%'>"+_("切工")+"</th>";
                        $thead+="<th style='width:10%'>"+_("抛光")+"</th>";
                        $thead+="<th style='width:10%'>"+_("对称")+"</th>";
                        $thead+="<th style='width:10%'>"+_("荧光")+"</th>";
                    }else if(params.IsFancy == 0 && discount_td==true&&CurrentUSD==true && USDprice_td==true && discountsUSD_td){
                        $thead+="<th style='width:10%'>"+_("切工")+"</th>";
                        $thead+="<th style='width:10%'>"+_("抛光")+"</th>";
                        $thead+="<th style='width:10%'>"+_("对称")+"</th>";
                        $thead+="<th style='width:10%'>"+_("荧光")+"</th>";
                    }else {
                        if(params.IsFancy == 0 && discount_td==true){
                            $thead+="<th style='width:10%'>"+_("切工")+"</th>";
                            $thead+="<th style='width:10%'>"+_("抛光")+"</th>";
                            $thead+="<th style='width:13%'>"+_("对称")+"</th>";
                            $thead+="<th style='width:13%'>"+_("荧光")+"</th>";
                        }else if(CurrentRMB==true && RMBprice_td==true){
                            $thead+="<th style='width:10%'>"+_("切工")+"</th>";
                            $thead+="<th style='width:10%'>"+_("抛光")+"</th>";
                            $thead+="<th style='width:13%'>"+_("对称")+"</th>";
                            $thead+="<th style='width:13%'>"+_("荧光")+"</th>";
                        }else {
                            if(CurrentUSD==true && USDprice_td==true){
                                $thead+="<th style='width:10%'>"+_("切工")+"</th>";
                                $thead+="<th style='width:10%'>"+_("抛光")+"</th>";
                                $thead+="<th style='width:13%'>"+_("对称")+"</th>";
                                $thead+="<th style='width:13%'>"+_("荧光")+"</th>";
                            }else {
                                $thead+="<th style='width:17%'>"+_("切工")+"</th>";
                                $thead+="<th style='width:18%'>"+_("抛光")+"</th>";
                                $thead+="<th style='width:17%'>"+_("对称")+"</th>";
                                $thead+="<th style='width:18%'>"+_("荧光")+"</th>";
                            }
                        }
                    }


                    if(params.IsFancy == 0 && discount_td==true){
                        $thead+="<th style='width:13%'>"+_("退点")+"<i class='sort sort_asc'  data-sort-direct='asc'  data-sort='CustomerDiscountReturn'></i></th>";
                    }


                    // if(CurrentRMB==true && RMBprice_td==true){ //仅美金
                    //     $thead+="<th style='width:13%'>"+_("总价 ")+"<i class='sort sort_normal'  data-sort='CustomerRMBPerGrain'></i></th>";
                    // }else{ //全局0和人民币1显示人民币
                    //     if(CurrentUSD==true && USDprice_td==true){
                    //         $thead+="<th style='width:13%'>"+_("总价 ")+"<i class='sort sort_normal'  data-sort='CustomerRMBPerGrain'></i></th>";
                    //     }
                    // }

                    if(getcookie("lan") == "En" ){ //仅美金

                        $thead+="<th style='width:13%'>"+_("总价")+"<i class='sort sort_normal'  data-sort='CustomerRMBPerGrain'></i></th>";

                    }else{ //全局0和人民币1显示人民币USD

                        $thead+="<th style='width:13%'>"+_("总价")+"<i class='sort sort_normal'  data-sort='CustomerRMBPerGrain'></i></th>";
                    }

                    if(discountsUSD_td == true) {
                        if (CurrentUSD == true) {
                            $thead += "<th style='width:13%'>" + _("优惠$") + "</th>";
                        }
                    }
                    if(discountsRMB_td == true) {
                        if (CurrentRMB == true) {
                            $thead += "<th style='width:13%'>" + _("优惠￥") + "</th>";
                        }
                    }

                    $("#product_table_fixed thead tr,#product_table thead tr").html($thead);
                }else{
                    colspanVal=8;
                    ordering_SourceDiscountReturn= ShowColumn("ordering_SourceDiscountReturn");
                    ordering_SourceDolarPerCarat= ShowColumn("ordering_SourceDolarPerCarat");
                    ordering_SourceDolarPerGrain= ShowColumn("ordering_SourceDolarPerGrain");
                    ordering_Supplier = ShowColumn("ordering_Supplier");//供应商
                    ordering_RMBPerGrain = ShowColumn("ordering_RMBPerGrain");//￥/Pcs
                    ordering_RMBPerCarat = ShowColumn("ordering_RMBPerCarat");//￥/Ct
                    ordering_DolarPerGrain = ShowColumn("ordering_DolarPerGrain");//$/Pcs

                    ordering_DolarPerCarat = ShowColumn("ordering_DolarPerCarat");//$/Ct
                    ordering_DiscountReturn = ShowColumn("ordering_DiscountReturn");//退点
                    ordering_Rapnet = ShowColumn("ordering_Rapnet");//Rap
                    var $thead_html="<th style='width:8%'></th>"+
                        "<th style='width:10%'>"+_("重量")+"</th>"+
                        "<th style='width:10%'>"+_("颜色")+"</th>"+
                        "<th style='width:10%'>"+_("净度")+"</th>"+
                        "<th style='width:10%'>"+_("切工")+"</th>"+
                        "<th style='width:10%'>"+_("抛光")+"</th>"+
                        "<th style='width:10%'>"+_("对称")+"</th>"+
                        "<th style='width:10%'>"+_("荧光")+"</th>";
                    if(params.IsFancy == 0 ) {
                        if (ordering_DiscountReturn == 1 || RoleID == 1) {
                        colspanVal++;
                        $thead_html += "<th class='white_show' style='width:15%'>" + _("退点") + "<i class='sort sort_asc' data-sort-direct='asc'  data-sort='CustomerDiscountReturn'></i></th>";
                        }
                    }
                    if(ordering_DolarPerGrain == 1 || ordering_RMBPerGrain==1  || RoleID == 1){
                        colspanVal++;
                        $thead_html+="<th style='width:15%'>"+_("总价")+"<i class='sort sort_normal' data-sort='CustomerRMBPerGrain'></i></th>";
                    }
                    $("#product_table thead tr,#product_table_fixed thead tr").html($thead_html);
                }

                if (_result.data.Data.length== 0) {
                    //无结果
                    var tr = "";//单行
                    var tds = "<td colspan='12' style='text-align:center;color:red'>"+_("没有符合条件的结果")+"</td>";// 多列合成一列并居中
                    tr = "<tr>" + tds + "</tr>";//将多列加到一行
                    tableTbody.html(tr);//加入到id为customer的table的tbody中
                } else {
                    var _res = _result.data.Data;//object
                    sortNewData(_res); //默认排序
                    getGoodsSort();
                    //SortJson = SortJson.concat(_res); //合并数组
                    SortJson = _res; //合并数组
                    bindingInventory(_res);//绑定白钻
                    $("body").scrollTop(0);
                }
            }else {
                //获取库存失败
                var tr = "";//单行

                if(TEAM==0){
                    var isLogin=getcookie("CustomerID");//客户
                    if(isLogin==null || isLogin=="(null)" || !isLogin ||isLogin=='nil'){
                        var tds = "<td colspan='9' style='text-align:center;color:red'>未搜索到相关数据</td>";// 多列合成一列并居中
                    }else{
                        var tds = "<td colspan='9' style='text-align:center;color:red'>" + _(_result.msginfo) + "</td>";// 多列合成一列并居中
                    }
                }else{
                    var tds = "<td colspan='12' style='text-align:center;color:red'>" + _(_result.msginfo) + "</td>";// 多列合成一列并居中
                }
                tr = "<tr>" + tds + "</tr>";//将多列加到一行
                tableTbody.html(tr);//加入到id为customer的table的tbody中
            }
            myApp.hideIndicator();//隐藏加载中

        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            // myApp.hideIndicator();//隐藏加载中
            myApp.alert("网络超时，请重试");
        },
    });
}

//绑定数据
function bindingInventory(_result) {
    var tableTbody = $("#stock_body");

    var trs = "";//多行数据
    for (var i = 0; i < _result.length; i++) {
        if (_result[i].IsFancy == 1) {
            $(".fancy_show").show();
            $(".white_show").hide();
        } else {
            $(".white_show").show();
            $(".fancy_show").hide();
        }

        var tds = "";//多列
        var tr = "";//单行
        var tr_div = "";
        var data=_result[i];
        if(TEAM==0 || TEAM==3){
            if (data.Status == 1 || data.Status == 3 || data.Status == 6){ //在库与实验室可下单 报关中
                tds += "<td class='check_rel'>"+
                    "<div class='check_list_box'><span class='checkbox' name='checkbox' lang='" + data.ID + "' data-usd='"+
                    formatUSDPrice(data.CustomerDolarPerGrain)+"' data-rmb='" + formatRMBPrice(data.CustomerRMBPerGrain) + "'></span></div></td>";
                tds += "<td class='check_list_td'>" + data.Weight + "</td>";
            }else{
                tds += "<td>"+
                    "<div class='check_list_box'></td>";
                tds += "<td>" + data.Weight + "</td>";
            }
        }else{
            tds +="<td></td>";
            tds += "<td>" + data.Weight + "</td>";
        }
        tds += "<td class='check_list_td2'>" +ColorFormat(data.Color) + "</td>";
        tds += "<td>" + data.Clarity + "</td>";
        tds += "<td>" + data.Cut + "</td>";
        tds += "<td>" + data.Polish + "</td>";
        tds += "<td>" + data.Symmetry + "</td>";
        tds += "<td>" + data.Fluorescence + "</td>";
        if(TEAM==0 || TEAM ==3){//客户端  代下单
            if (data.IsFancy == 0 && discount_td==true) {
                tds += "<td>" + ValueFormat(data.CustomerDiscountReturn) + "</td>";
            }

            // if(CurrentRMB==true && RMBprice_td==true){ //仅美金
            //     tds += "<td style='font-weight:bold' class=''>" + formatRMBPrice(data.CustomerRMBPerGrain) + "</td>";//四舍五入
            // }else{ //全局0和人民币1显示人民币
            //     if(CurrentUSD==true && USDprice_td==true){
            //         tds += "<td style='font-weight:bold' class=''>" + formatUSDPrice(data.CustomerDolarPerGrain) + "</td>";//四舍五入
            //     }
            // }
            if(getcookie("lan") == "En"){
                if(CurrentRMB == true && CurrentUSD==true){
                    tds += "<td style='font-weight:bold' class=''>" + formatRMBPrice(data.CustomerRMBPerGrain)   + "</td>";//四舍五入
                }else if(CurrentUSD == true){
                    tds += "<td style='font-weight:bold' class=''>" + formatUSDPrice(data.CustomerDolarPerGrain) + "</td>";//四舍五入
                }else if(CurrentRMB==true){
                    tds += "<td style='font-weight:bold' class=''>" + formatRMBPrice(data.CustomerRMBPerGrain) + "</td>";//四舍五入
                }
            }else{
                if(CurrentRMB){
                    tds += "<td style='font-weight:bold' class=''>" + formatRMBPrice(data.CustomerRMBPerGrain) + "</td>";//四舍五入
                }else if(CurrentUSD ){
                    tds += "<td style='font-weight:bold' class=''>" + formatUSDPrice(data.CustomerDolarPerGrain) + "</td>";//四舍五入
                } else{
                    tds += "<td style='font-weight:bold' class=''>" + formatRMBPrice(data.CustomerRMBPerGrain) + "</td>";//四舍五入
                }
                // tds += "<td style='font-weight:bold' class=''>" + formatRMBPrice(data.CustomerRMBPerGrain) + "</td>";//四舍五入
            }

            if(TEAM==0){
                if(discountsUSD_td == true) {
                    if (CurrentUSD == true) {
                        tds += "<td style='color:#0099ff'>" + formatUSDPrice(data.CustomerDolarPerGrain*Discounts) + "</td>";
                    }
                }
                if(discountsRMB_td == true) {
                    if (CurrentRMB == true) {
                        tds += "<td style='color:#0099ff'>" + formatRMBPrice(data.CustomerRMBPerGrain*Discounts) + "</td>";
                    }
                }
            }

        }else{//团队端
            if (data.IsFancy == 0) {
                if(ordering_DiscountReturn==1  || RoleID == 1)
                    tds += "<td>" + ValueFormat(data.DiscountReturn) + "</td>";
            }
            if(CurrentRMB==true){ //全局0和人民币1显示人民币
                if(ordering_RMBPerGrain==1  || RoleID == 1)
                    tds += "<td style='font-weight:bold' class=''>" + formatRMBPrice(data.RMBPerGrain) + "</td>";//四舍五入
            }else{ //美金
                if(ordering_DolarPerGrain==1  || RoleID == 1)
                    tds += "<td style='font-weight:bold' class=''>" + formatUSDPrice(data.DolarPerGrain) + "</td>";//四舍五入
            }
        }

        tr += "<tr class='data_tr'>" + tds + "</tr>";//将多列加到一行onclick=\"click_change_tr_color(this)\"
        if(TEAM==0){
            if(data.IsFancy == 0){
                tr_div="<tr class='stock_detail'><td  colspan='12'>";
            }else{
                if(discountsRMB_td == true || discountsUSD_td ==true){
                    tr_div="<tr class='stock_detail'><td  colspan='10'>";
                }else{
                    tr_div="<tr class='stock_detail'><td  colspan='9'>";
                }
            }
            tr_div+="<div class='detail_left' style='width:50%;'>";
            if(OriginSN_td==true){
                tr_div+="<i onclick='showTotalWord(this)'><b class='custrom'>"+_("原货号")+"：</b><span>" + data.OriginSN + "</span></i>";
            }
            if(SN_td==true){
                tr_div+="<i onclick='showTotalWord(this)'><b class='custrom'>"+_("货号")+"：</b><span>" + data.SN + "</span></i>";
            }
            tr_div+="<i><b>"+_("形状")+"：</b>"+GetText("stocks",1,data.Shape,"Shape")+"</i>"+
                "<i><b>"+_("奶油")+"：</b>" + MilkyFormat(data.Milky) + "</i>" +
                "<i><b>"+_("色调")+"：</b>" + HueFormat(data.Hue) + "</i>" +
                "<i><b>"+_("心箭")+"：</b>" + HAFormat(data.HA) + "</i>" +
                "<i onclick='showTotalWord(this)'><b class='custrom'>"+_("黑点")+"：</b><span>" + BlackDefectFormat(data.BlackDefect) + "</span></i>" +
                "<i onclick='showTotalWord(this)'><b class='custrom'>"+_("瑕疵")+"：</b><span>" + OtherDefectFormat(data.OtherDefect) + "</span></i>";
            if(cert_td==true && certNo_td==true){
                tr_div+="<i><b>"+_("证书")+"：</b>" + CertTypeFormat(data) + "</i>";
            }else if(cert_td==true){
                tr_div+="<i><b>"+_("证书")+"：</b>" + data.CertType + "</i>";
            }
            if(place_td==true){
                tr_div+="<i><b>"+_("所在地")+"：</b>" + GetText("stocks",data.IsFancy,data.Place,"Place") + "</i>";
            }
            if(CurrentRMB==true){
                tr_div+="<i><b>"+_("汇率")+"：</b>" + $.cookie("DiasRate")+ "</i>";
            }
            if(tablePct_td==true){

                tr_div+="<i><b>"+_("台宽比")+"：</b>" + TableFormat(data.TablePct)+ "</i>";
            }
            if(depthPct_td==true){

                tr_div+="<i><b>"+_("全深比")+"：</b>" + DepthFormat(data.DepthPct)+ "</i>";
            }

            tr_div+="</div>" +
                "<div class='detail_right' style='width:50%;'>";
            if(certNo_td==true){
                tr_div+="<i onclick='showTotalWord(this)'><b class='custrom'>"+_("证书号")+"：</b><span>" + NullFormat(data.CertNo) + "</span></i>";
            }
            tr_div+="<i><b>"+_("状态")+"：</b>" + GetText("stocks",1,data.Status,"Status") + "</i>";
            if(rap_td==true){
                tr_div+="<i><b>"+_("Rap")+"：</b>" + formatUSDPrice(data.Rapnet) + "</i>" ;
            }

            tr_div+="<i onclick='showTotalWord(this)'><b class='custrom'>"+_("尺寸")+"：</b><span>" + NullFormat(data.Measurement) + "</span></i>"+
                "<i><b>"+_("发货")+"：</b>" + GetDateByWeek(data.ShipTime) + "</i>";
            if(UpdateTime_td==true){
                tr_div+="<i><b class='custrom'>"+_("上架")+"：</b>" + DateTimeHandler(data.UpdateTime) + "</i>";
            }
            tr_div+=showDiaPrice(data);

            if(APP)  //客户端
                tr_div+="<i><span id='order_btnUp' data-da='"+JSON.stringify(data)+"' onclick='orderBtn(this)' class='order_btn' style='background-color: #f80;width:40px;height:26px;color:#fff;margin-bottom: 5px;border-radius: 5px;text-align: center;margin-left:65px'>分享</span></i>";

            tr_div+="</div></td></tr>";
        }else{
            tr_div="<tr class='stock_detail'><td  colspan="+colspanVal+">";
            tr_div+="<div class='detail_left' style='width:50%;'>"+
                "<i onclick='showTotalWord(this)'><b class='custrom'>"+_("货号")+"：</b><span>" + data.SN + "</span></i>"+
                "<i><b>"+_("形状")+"：</b>"+GetText("stocks",1,data.Shape,"Shape")+"</i>"+
                "<i><b>"+_("奶油")+"：</b>" + MilkyFormat(data.Milky) + "</i>" +
                "<i><b>"+_("色调")+"：</b>" + HueFormat(data.Hue) + "</i>" +
                "<i><b>"+_("心箭")+"：</b>" + HAFormat(data.HA) + "</i>" +
                "<i onclick='showTotalWord(this)'><b class='custrom'>"+_("黑点")+"：</b><span>" + BlackDefectFormat(data.BlackDefect) + "</span></i>" +
                "<i onclick='showTotalWord(this)'><b class='custrom'>"+_("瑕疵")+"：</b><span>" + OtherDefectFormat(data.OtherDefect) + "</span></i>"+
                "<i><b>"+_("证书")+"：</b>" + CertTypeFormat(data) + "</i>"+
                showDiaPrice(data)+
                "</div>" +
                "<div class='detail_right' style='width:50%;'>"+
                "<i onclick='showTotalWord(this)'><b class='custrom'>"+_("证书号")+"：</b><span>" + NullFormat(data.CertNo) +"</span></i>";
            if(data.IsFancy==0 && ordering_Rapnet==1)
                tr_div+="<i><b>"+_("Rap")+"：</b>" + formatUSDPrice(data.Rapnet) + "</i>";
            tr_div+="<i><b>"+_("所在地")+"：</b>" + PlaceFormat(data.Place) + "</i>"+
                "<i><b>"+_("状态")+"：</b>" + GetText("stocks",1,data.Status,"Status") + "</i>";
            if(isHideSupplier == "1"){
                if(ordering_Supplier==1 || RoleID == 1){
                    tr_div+="<i><b class='custrom' style='width:auto'>"+_("供应商")+"：</b>"+
                        "<span style='color:red' onclick='Contact_Js(this)' value="+data.Supplier+">" + NullFormat(data.Supplier) + "</span></i>";
                }

            }

            tr_div+="<i onclick='showTotalWord(this)'><b class='custrom'>"+_("原货号")+"：</b><span>" + data.OriginSN + "</span></i>";
            if(data.IsFancy == 0 ) {
                if( ordering_SourceDiscountReturn ==1 || RoleID == 1){
                    tr_div += "<i onclick='showTotalWord(this)'><b class='custrom'>" + _("原退") + "：</b><span>" + data.SourceDiscountReturn + "</span></i>";
                }
            }
            if(ordering_SourceDiscountReturn===1 || RoleID == 1)
                tr_div+="<i><b>"+_("原退点")+"：</b>" + data.SourceDiscountReturn + "</i>";
            if(ordering_SourceDolarPerCarat==1 || RoleID == 1)
                tr_div+="<i class='CurrentUSD'><b>"+_("原")+"$/Ct：</b>" + formatUSDPrice(data.SourceDolarPerCarat) + "</i>";
            if(ordering_SourceDolarPerCarat==1 || RoleID == 1)
                tr_div+="<i class='CurrentUSD'><b>"+_("原")+"$：</b>" + formatUSDPrice(data.SourceDolarPerGrain) + "</i>" ;
            tr_div+="<i onclick='showTotalWord(this)'><b class='custrom'>"+_("尺寸")+"：</b><span>" + NullFormat(data.Measurement) + "</span></i>";
            tr_div+="<i><b>"+_("发货时间")+"：</b>" + GetDateByWeek(data.ShipTime) + "</i>";
            tr_div+="<i><b class='custrom'>"+_("上架")+"：</b>" + DateTimeHandler(data.UpdateTime) + "</i>";


            if(APP)  //团队端
                tr_div+="<i><span id='order_btnUp' data-da='"+JSON.stringify(data)+"' onclick='orderBtn(this)' class='order_btn' style='background-color: #f80;width:40px;height:26px;color:#fff;margin-bottom: 5px;border-radius: 5px;text-align: center;margin-left:65px'>分享</span></i>";

            tr_div+="</div></td></tr>";
        }

        trs += tr+tr_div;//将单行加到多行
    }
    tableTbody.html(trs);//加入到id为customer的table的tbody中
    currentShow();  //币种设置
}


//按退点默认排序
function sortNewData(data){
    var newData=data;
    newData.sort(function(a,b){
        // if(TEAM ==0 || TEAM ==3){
            return a.CustomerDiscountReturn-b.CustomerDiscountReturn;
        // }else{
        //     return a.DiscountReturn-b.DiscountReturn;
        //
        // }
    })
}

// 获取图片和视频
function GetImgHd(data){
    var str = "";
    if(data.HasImage==1){
        str +='<img alt="图片" src="/images/imageIcon.png" class="ImageIcon" />';
    }
    if(data.HasVideo==1){
        str+='<img alt="视频" src="/images/videoIcon.png" class="VideoIcon" />'
    }
    return str;
}

//提交
function orderBtn(data){

    if(APP){
        $("#order_btnUp").css({'display':'block'});

        var data_val=JSON.parse($(data).attr('data-da'));
        //console.log(data_val)

        var appJson={};
        appJson.title="裸钻—白钻";

        appJson.text=""+ShapeFormat(data_val.Shape)+" "+data_val.Weight+" "+data_val.Color+" "+" "+data_val.Clarity+" "+" "+data_val.Cut+" "+" "+data_val.Polish+" ";
        appJson.text +=""+data_val.Symmetry+" "+data_val.Fluorescence+" "+data_val.Measurement+" "+" "+data_val.CertType+" ";
        appJson.copy_text=appJson.text;
        appJson.images=[];

        var other_info={};
        other_info.certNo=data_val.CertNo
        other_info.goods_type="stock";
        if(TEAM==0 || TEAM ==3){
            other_info.discount=ValueFormat(data_val.CustomerDiscountReturn);
        }else{
            other_info.discount=ValueFormat(data_val.DiscountReturn);

        }
        other_info.weight=data_val.Weight;
        other_info.unit_price_rmb=data_val.CustomerRMBPerCarat;
        other_info.total_price_rmb=data_val.CustomerRMBPerGrain;
        other_info.unit_price_dollar=data_val.CustomerDolarPerCarat;
        other_info.total_price_dollar=data_val.CustomerDolarPerGrain;
        other_info.cert_type=data_val.CertType;  //GIA

        var internationalRmb=data_val.Rapnet*Number($.cookie("DiasRate"))
        other_info.international_quotation_rmb=internationalRmb;
        other_info.international_quotation_dollar=data_val.Rapnet;
        other_info.rate=Number($.cookie("DiasRate"));
        appJson.other_info=other_info;

        appJson.url="";

        //console.log(appJson);

        YiYi_APP.share(JSON.stringify(appJson));
    }
}

function ShapeFormat(shapeValue) {
    if (shapeValue == 1) {
        return _("圆形");
    }  else if (shapeValue == 2) {
        return _("公主方");
    } else if (shapeValue == 3) {
        return _("祖母绿");
    } else if (shapeValue == 4) {
        return _("雷迪恩");
    } else if (shapeValue == 5) {
        return _("椭圆形");
    } else if (shapeValue == 6) {
        return _("梨形");
    } else if (shapeValue == 7) {
        return _("马眼形");
    }else if (shapeValue == 8) {
        return _("心形");
    }  else if (shapeValue == 9) {
        return _("三角形");
    }else if (shapeValue == 10) {
        return _("垫形");
    } else if (shapeValue == 11) {
        return _("其它");
    }else if (shapeValue == 12) {
        return _("梯形");
    } else if (shapeValue == 13) {
        return _("直方");
    } else if (shapeValue == 14) {
        return _("组合");
    }
    return _("其它");
}
 
//供应商联系方式
function Contact_Js(me) {
    myApp.showIndicator();
    $.ajax({
        url: "/Team/ContactSupplier",//提交地址
        type: "POST",//提交方式
        data: "{'SupplierCode':'" + me.getAttribute("value") + "'}",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if (_result.msgcode == false) {
                myApp.alert(_result.msginfo);
            } else {
                var _result = eval('(' + _result + ')');//再次解析_result

                if (_result.result == true) {
                    $("#_company").val(_result.Company);
                    $("#_shortName").val(_result.ShortName);
                    $("#_website").val(_result.Contact.Website);//json.json.json
                    $("#_qq").val(_result.Contact.QQ);
                    $("#_name").val(_result.Contact.Name); //Telephone
                    $("#_telephone").val(_result.Contact.Telephone);
                    $("#_rapid").val(_result.Contact.RapID);
                    //$("#_skype").val(_result.Contact.Skype);
                    if (_result.Contact.Skype != "") {
                        $("#_skype").html("<b style='font-size:20px;' title='点击和" + _result.Contact.Skype +
                            "聊天'><span><img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1489148014986&di=253cba520b4b4c293c60f95cabd708db&imgtype=0&src=http%3A%2F%2Fimg.download.pchome.net%2F3p%2F7b%2Flogo.jpg' style='border: none;width:20px;height:20px;' /></span><label>" +
                            _result.Contact.Skype + "</label></b>");//点击打开Skype
                    } else {
                        $("#_skype").html("");
                    }
                    $("#_email").val(_result.Contact.Email);
                    $("#_wechat").val(_result.Contact.WeChat);
                    $("#_mobilephone").val(_result.Contact.MobilePhone);
                    $("#_address").val(_result.Address.Country + "-" + _result.Address.State + "-" + _result.Address.City);//中国-广东-深圳
                    myApp.popup(".Contact_box");
//                  $(".Contact_box").show();
                } else {
                    //暂无联系方式
                    myApp.alert(_("该供应商暂无联系方式"));
                }
            }
            myApp.hideIndicator();
        }
    });
}


function showDiaPrice(data){
    if(TEAM == 0 || TEAM ==3){
        var str ="";
        if(CurrentUSD==true && USDperPrice_td==true){
            str +="<i class='CurrentUSD'><b>$/Ct：</b>"+formatUSDPrice(data.CustomerDolarPerCarat)+"</i>";
        }
        if(CurrentUSD==true && USDprice_td==true){
            str +="<i class='CurrentUSD'><b>$/Pcs：</b>" + formatUSDPrice(data.CustomerDolarPerGrain) + "</i>";
        }
        if(CurrentRMB==true && RMBperPrice_td==true){
            str +="<i class='CurrentRMB'><b>￥/Ct：</b>" + formatRMBPrice(data.CustomerRMBPerCarat) + "</i>";
        }
        if(CurrentRMB==true && RMBprice_td==true){
            str +="<i class='CurrentRMB'><b>￥/Pcs：</b>" + formatRMBPrice(data.CustomerRMBPerGrain) + "</i>";
        }
        str += "<i data-value = '"+data.ID+"'><b>"+_("图片")+"：</b>" + GetImgHd(data) + "</i>";
        return str;
    }else{
        var str = "";
        if(CurrentUSD==true){
            if(ordering_DolarPerCarat==1 || RoleID == 1)
                str +="<i><b>$/Ct：</b>"+formatUSDPrice(data.DolarPerCarat)+"</i>";
            if(ordering_DolarPerGrain==1 || RoleID == 1)
                str +="<i><b>$/Pcs：</b>" + formatUSDPrice(data.DolarPerGrain) + "</i>";
        }
        if(CurrentRMB==true){
            if(ordering_RMBPerCarat==1 || RoleID == 1)
                str +="<i><b>￥/Ct：</b>" + formatRMBPrice(data.RMBPerCarat) + "</i>";
            if(ordering_RMBPerGrain==1 || RoleID == 1)
                str +="<i><b>￥/Pcs：</b>" + formatRMBPrice(data.RMBPerGrain) + "</i>";
        }
        str +="<i data-value = '"+data.ID+"'><b>"+_("图片")+"：</b>" + GetImgHd(data) + "</i>";
        str+="<i><b>"+_("台宽比")+"：</b>" + TableFormat(data.TablePct)+ "</i>";
        str+="<i><b>"+_("全深比")+"：</b>" + DepthFormat(data.DepthPct)+ "</i>";
        return str;
    }
}


//格式化台宽比
function TableFormat(rapnetValue) {
    if(rapnetValue){
        return rapnetValue.toFixed(0)
    }else{
        return '';
    }
    return rapnetValue;
}

//格式化全深比
function DepthFormat(rapnetValue) {
    if(rapnetValue){
        return rapnetValue.toFixed(1)
    }else{
        return '';
    }
    return rapnetValue;
}